import {getSongLyric} from 'api/song'
import {ERR_OK} from 'api/config'
import {Base64} from 'js-base64'

/**
 * 封装的歌曲类
 */
export default class Song {
  constructor ({id, mid, singer, name, album, duration, image, url}) {
    this.id = id
    this.mid = mid
    this.singer = singer
    this.name = name
    this.album = album
    this.duration = duration
    this.image = image
  }
  getLyric () {
    if (this.lyric) {
      return Promise.resolve(this.lyric)
    }
    return new Promise((resolve, reject) => {
      getSongLyric(this.mid).then(res => {
        if (res.retcode === ERR_OK) {
          this.lyric = Base64.decode(res.lyric)
          resolve(this.lyric)
        } else {
          reject(new Error('no lyric'))
        }
      })
    })
  }
}

/**
 * 创建歌曲对象的方法
 * @param musicData {JSON} 获取的JSON数据中songlist中的item
 * @return {Song}
 */
export function createSong (musicData) {
  return new Song({
    id: musicData.id,
    mid: musicData.mid,
    name: musicData.name,
    album: musicData.album.name,
    duration: musicData.interval,
    image: `https://y.gtimg.cn/music/photo_new/T002R500x500M000${musicData.album.mid}.jpg`,
    singer: filterSinger(musicData.singer)
  })
}

/**
 * 拼接一首歌的多个歌手
 * @param singers {Array} 所有歌手的数据
 * @return {string}
 */
export function filterSinger (singers) {
  if (!singers) {
    return ''
  }
  let result = []
  singers.forEach(item => {
    result.push(item.name)
  })
  return result.join('/')
}
